package com.hyc.myvideo.ui.activity.home;

import android.content.Intent;
import android.media.MediaPlayer;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.TextView;

import com.acmenxd.toaster.Toaster;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.flyco.tablayout.SlidingTabLayout;
import com.hyc.myvideo.R;
import com.hyc.myvideo.data.api.constants.Constants;
import com.hyc.myvideo.data.api.model.BaseResult;
import com.hyc.myvideo.data.api.model.CurriculumHour;
import com.hyc.myvideo.ui.base.BaseFActivity;
import com.hyc.myvideo.ui.base.BaseFragment;
import com.hyc.myvideo.ui.fragment.home.CommentFragment;
import com.hyc.myvideo.ui.fragment.home.CourseInfoFragment;
import com.hyc.myvideo.ui.service.OnVideoEventListener;
import com.hyc.myvideo.ui.view.MNViderPlayer;
import com.hyc.utils.StringUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import timber.log.Timber;

/**
 * 视频播放
 * Created by dfeads on 2017/7/22.
 */

public class VideoActivity extends BaseFActivity {
  /** 标题 */
  @BindView(R.id.activity_video_title) TextView mTitle;
  /** 人数 */
  @BindView(R.id.activity_video_num) TextView mNum;
  /** 课程简介 标题 */
  @BindView(R.id.activity_video_more_course_info) TextView mInfo;
  /** 评论条数 */
  @BindView(R.id.activity_video_more_comment) TextView mComment;
  @BindView(R.id.activity_video_more_stl) SlidingTabLayout mTable;
  @BindView(R.id.activity_video_more_vp) ViewPager mPager;
  @BindView(R.id.activity_video_player) MNViderPlayer mnViderPlayer;

  //private final String url2 ="http://mp4.vjshi.com/2017-05-10/293b7a2a1c8834a06938e1ab955627ad.mp4";
  private final String url2 = "http://bvideo.spriteapp.cn/video/2016/0704/577a4c29e1f14_wpd.mp4";

  private final String[] mTitles = { "课程简介", "评论(255)" };
  private List<BaseFragment> fragments = new ArrayList<>();
  private MyPagerAdapter mAdapter;
  private String curriculum_hour_id = "";

  private CourseInfoFragment courseInfoFragment;
  private CommentFragment commentFragment;
  private CurriculumHour curriculumHour;

  @Override public int getContentViewId() {
    return R.layout.activity_video;
  }

  @Override protected void initView() {
    curriculum_hour_id = getIntent().getStringExtra("id");
    if (!StringUtils.isEmpty(curriculum_hour_id)) {
      api.getHomeClassHourDetails(curriculum_hour_id);
    }
    courseInfoFragment = new CourseInfoFragment();
    commentFragment = new CommentFragment();
    commentFragment.setCurriculum_hour_id(curriculum_hour_id);
    fragments.add(courseInfoFragment);
    fragments.add(commentFragment);

    mAdapter = new MyPagerAdapter(getSupportFragmentManager());
    mPager.setAdapter(mAdapter);
    mTable.setViewPager(mPager);
    mInfo.setTextColor(getResources().getColor(R.color.color_1));

    mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
      @Override
      public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
      }

      @Override public void onPageSelected(int position) {

        switch (position) {
          case 0:
            mInfo.setTextColor(getResources().getColor(R.color.color_1));
            mComment.setTextColor(getResources().getColor(R.color.color_2));
            break;
          case 1:
            mInfo.setTextColor(getResources().getColor(R.color.color_2));
            mComment.setTextColor(getResources().getColor(R.color.color_1));
            break;
        }
      }

      @Override public void onPageScrollStateChanged(int state) {
      }
    });

    //初始化相关参数(必须放在Play前面)
    mnViderPlayer.setWidthAndHeightProportion(16, 9);   //设置宽高比
    mnViderPlayer.setIsNeedNetChangeListen(true);       //设置网络监听
    //第一次进来先设置数据
    mnViderPlayer.setDataSource(url2);

    mnViderPlayer.setVideoEventListener(new OnVideoEventListener() {
      @Override public void onFinish() {
        finish();
      }

      @Override public void onDownload() {
        Toaster.show("下载");
      }

      @Override public void onAddToCatalog() {
        startActivity(
            new Intent(VideoActivity.this, TrainingCatalogSecActivity.class).putExtra("id",
                curriculumHour.getCurriculum_id()));
      }

      @Override public void onShare() {
        Toaster.show("分享");
      }
    });

    //播放完成监听
    mnViderPlayer.setOnCompletionListener(new MNViderPlayer.OnCompletionListener() {
      @Override public void onCompletion(MediaPlayer mediaPlayer) {
        Timber.e("======video====onCompletion========");
        api.setUserPracticeRecord(userInfo.getUser_id(), curriculum_hour_id,
            mediaPlayer.getDuration() + "");
      }
    });
  }

  @Override protected void initData() {

  }

  @Override protected void oNext(String resulte, String method) {
    //课时详情
    if (method.equals(Constants.API_CURRICULUM_HOUR_DETAILS)) {
      BaseResult<CurriculumHour> curriculums =
          JSONObject.parseObject(resulte, new TypeReference<BaseResult<CurriculumHour>>() {
          });
      if (curriculums.isCode()) {
        curriculumHour = curriculums.getResult();
        //mnViderPlayer.setDataSource(curriculumHour.getCurriculum_hour_url());
        courseInfoFragment.setContent(curriculumHour.getCurriculum_hour_text());
        setView();
      } else {
        Toaster.show(curriculums.getMsg());
      }//课时时长
    } else if (method.equals(Constants.API_PRACTICE_SET_USER_PRACTICE_RECORD)) {
      BaseResult<String> base =
          JSONObject.parseObject(resulte, new TypeReference<BaseResult<String>>() {
          });
      if (base.isCode()) {

      }
      Toaster.show(base.getMsg());
    }
  }

  @Override protected void oError() {

  }

  private void setView() {
    if (curriculumHour == null) {
      return;
    }

    mTitle.setText(curriculumHour.getCurriculum_hour_title());
    mComment.setText("评论(" + curriculumHour.getHour_comment_count() + ")");
  }

  @OnClick({
      R.id.activity_video_more_course_info, R.id.activity_video_more_comment
  }) public void onViewClicked(View view) {
    switch (view.getId()) {
      case R.id.activity_video_more_course_info://课程简介
        mPager.setCurrentItem(0);
        break;
      case R.id.activity_video_more_comment://评论
        mPager.setCurrentItem(1);
        break;
    }
  }

  @Override protected void onPause() {
    super.onPause();
    //暂停
    mnViderPlayer.pauseVideo();
  }

  @Override public void onBackPressed() {
    if (mnViderPlayer.isFullScreen()) {
      mnViderPlayer.setOrientationPortrait();
      return;
    }
    super.onBackPressed();
  }

  @Override protected void onDestroy() {
    //一定要记得销毁View
    if (mnViderPlayer != null) {
      mnViderPlayer.destroyVideo();
      mnViderPlayer = null;
    }
    super.onDestroy();
  }

  private class MyPagerAdapter extends FragmentPagerAdapter {

    public MyPagerAdapter(FragmentManager fm) {
      super(fm);
    }

    @Override public Fragment getItem(int position) {
      return fragments.get(position);
    }

    @Override public int getCount() {
      return mTitles.length;
    }

    @Override public CharSequence getPageTitle(int position) {
      return mTitles[position];
    }
  }
}
